package jjn.round1;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author Jjn
 * @since 2022/8/30 00:14
 */
public class LeetCode116_PopulatingNextRightPointersInEachNode {
    
    public static class Node {
        int val;
        Node left;
        Node right;
        Node next;
        
        public Node(int val) {
            this.val = val;
        }
    }
    
    public Node connect(Node root) {
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Queue<Node> level = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                Node poll = queue.poll();
                if (poll != null) {
                    poll.next = queue.peek();
                    if (poll.left != null) {
                        level.offer(poll.left);
                    }
                    if (poll.right != null) {
                        level.offer(poll.right);
                    }
                }
            }
            queue.addAll(level);
        }
        return root;
    }
}
